package com.example.androidstart;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.play.core.splitcompat.SplitCompat;
import com.google.android.play.core.splitinstall.SplitInstallManager;
import com.google.android.play.core.splitinstall.SplitInstallManagerFactory;
import com.google.android.play.core.splitinstall.SplitInstallRequest;
import com.google.android.play.core.splitinstall.SplitInstallSessionState;
import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener;
import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus;
import com.google.android.play.core.splitinstall.testing.FakeSplitInstallManager;
import com.google.android.play.core.splitinstall.testing.FakeSplitInstallManagerFactory;
import com.google.android.play.core.tasks.OnFailureListener;
import com.google.android.play.core.tasks.OnSuccessListener;

import java.util.Arrays;

public class AppBundleBaseActivity extends Activity implements SplitInstallStateUpdatedListener {
    private FakeSplitInstallManager splitInstallManager = null;
    private static final String TAG = "AppBundleBaseActivity";
    private int CONFIRMATION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_bundle_base);
        // Instantiate an instance of SplitInstallManager for the dynamic feature module
        splitInstallManager =
                FakeSplitInstallManagerFactory.create(AppBundleBaseActivity.this);

        findViewById(R.id.installFeature1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFeatureOne();
            }
        });
        findViewById(R.id.installtest).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent().setClassName(AppBundleBaseActivity.this.getPackageName(), "com.example.feature1.Feature1Activity");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        splitInstallManager.registerListener(this);
    }

    private int mSessionId;

    public void loadFeatureOne() {
        Log.d(TAG, "loadFeatureOne: split array is: " + Arrays.toString(splitInstallManager.getInstalledModules().toArray()));
        if (splitInstallManager.getInstalledModules().contains("feature1")) {
            Intent intent = new Intent().setClassName(AppBundleBaseActivity.this.getPackageName(), "com.example.feature1.Feature1Activity");
            startActivity(intent);
            return;
        }
        // Builds a request to install the feature1 module
        SplitInstallRequest request =
                SplitInstallRequest
                        .newBuilder()
                        // You can download multiple on demand modules per
                        // request by invoking the following method for each
                        // module you want to install.
                        .addModule("feature1")
                        .build();

        // Begin the installation of the feature1 module and handle success/failure
        splitInstallManager
                .startInstall(request)
                .addOnSuccessListener(new OnSuccessListener<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        // Module download successful
                        Log.d(TAG, "onSuccess: Module download successful");
                        mSessionId = integer;
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        // Module download failed; handle the error here
                        Toast.makeText(getApplicationContext(), "Couldn't download feature1: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    public void onStateUpdate(@NonNull SplitInstallSessionState state) {
        if (state.sessionId() != mSessionId) {
            Log.d(TAG, "onStateUpdate: session id not equal.");
            return;
        }
        //是否多模块安装
        boolean multiInstall = state.moduleNames().size() > 1;
        Log.d(TAG, "onStateUpdate: state.status()" + state.status());
        switch (state.status()) {
            case SplitInstallSessionStatus.DOWNLOADING:
                Log.d(TAG, "onStateUpdate: DOWNLOADING");
            case SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION:
                Log.d(TAG, "onStateUpdate: REQUIRES_USER_CONFIRMATION");
                try {
                    splitInstallManager.startConfirmationDialogForResult(state, this, CONFIRMATION_REQUEST_CODE);
                } catch (IntentSender.SendIntentException e) {
                    Log.d(TAG, "onStateUpdate: " + e);
                }
                break;
            case SplitInstallSessionStatus.INSTALLED:
                Log.d(TAG, "onStateUpdate: INSTALLED");
                Intent intent = new Intent().setClassName(getPackageName(), "com.example.feature1.Feature1Activity");
                startActivity(intent);
                break;
            case SplitInstallSessionStatus.INSTALLING:
                Log.d(TAG, "onStateUpdate: installing");
                break;
            case SplitInstallSessionStatus.FAILED:
                Log.d(TAG, "onStateUpdate: failed");
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CONFIRMATION_REQUEST_CODE) {
            // Handle the user's decision. For example, if the user selects "Cancel",
            // you may want to disable certain functionality that depends on the module.
            if (resultCode == Activity.RESULT_CANCELED) {
                toastAndLog("用户拒绝");
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    void toastAndLog(String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        Log.d(TAG, text);
    }

    @Override
    protected void onPause() {
        super.onPause();
        splitInstallManager.unregisterListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}